<?php
class Delivery_Model_Mapper_Categorias
	extends Delivery_Model_Mapper_Abstract
{
	
	public function getDbTable()
	{
		return parent::getDbTable( 'Categorias' );
	}
	
	public function save( $categoria )
	{
		$dbTable= $this->getDbTAble();
		
		if ( ! $categoria->getId() ){	
			return $categoria->idCategoria = $dbTable->insert( $categoria );
		} else {					
			return $dbTable->update( $categoria );	
		}	
		
	}
	
	public function delete( $categoria ){
	
		$mapper = Delivery_Model_Factory::mapper('Productos');
	 	$productos = $mapper->getByParams( array('idCategoria' => $categoria->idCategoria));
		
		if ( count($productos) ){
			throw new Delivery_Model_Exception( Delivery_Model_Exception::CATEGORY_CANNOT_BE_DELETED );
		}
				
		$dbTable= $this->getDbTAble();
		
		$this->logDeleted( $categoria );
		
		return $dbTable->delete( $categoria );
	}
	
	/**
	 * @param int $idCategoria
	 * @return object Delivery_Model_Categoria
	 */
	public function getById( $idCategoria ){
	
		if ( $this->getIdentityMap()->isRegistered( 'Delivery_Model_Categoria', $idCategoria )){
			return $this->getIdentityMap()->get( 'Delivery_Model_Categoria', $idCategoria );
		}
		
		$dbTable= $this->getDbTAble();
		$row	= $dbTable->getById( $idCategoria );
	
		if( empty($row) ){
			throw new Delivery_Model_Exception( Delivery_Model_Exception::CATEGORY_NOT_FOUND );
		}
		
		return $this->_fetch( $row );
	}
	
	/**
	 * @param array ids
	 *  @return Delivery_Model_Collection_Categorias
	 */
	public function getByIds( $ids )
	{
		$dbTable= $this->getDbTAble();
		
		return $this->_fetchCollection(
			'Categorias',
			$dbTable->getByIds( $ids )
		);
	}
	
	/**
	 * @param array ids
	 *  @return Delivery_Model_Collection_Categorias
	 */
	public function getByNegocio( $idNegocio )
	{
		$dbTable= $this->getDbTAble();
		
		return $this->_fetchCollection(
			'Categorias',
			$dbTable->getByNegocio( $idNegocio )
		);
	}
	
	/**
	 * @return Delivery_Model_Collection_Categorias
	 */
	public function getAll(){
	
		$dbTable= $this->getDbTAble();
			
		return $this->_fetchCollection(
			'Categorias',
			$dbTable->getAll()
		);
	}	
	
	/**
	 * @param array
	 * @return array objetos categoria
	 */
	public function getByParams( $params, $offset = null, $limit = null, $order = null ){
		
		$dbTable = $this->getDbTAble();
			
		return $this->_fetchCollection(
			'Categorias',
			$dbTable->getByParams( $params, $offset, $limit, $order )
		);
	}
	
	/**
	 * @param array
	 * @return int
	 */
	public function countByParams( $params ){
		return $this->getDbTAble()->countByParams($params);
	}
	
	
	/**
	 * @param array
	 * @return object Delivery_Model_Categoria
	 */
	protected function _fetch( $row )
	{
		$categoria = new Delivery_Model_Categoria( $row );
		
		$this->getIdentityMap()->set( $categoria, $categoria->getId() );
		
		return $categoria;
	}
	
}